package com.ymx.darling.mask;

import com.ymx.darling.exception.DarlingException;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

/**
 * 数据脱敏管理器
 * @author 爱Java的小于
 */
public class MaskManager {
    private static final Map<String, MaskProcessor> processorMap = new HashMap<>();
    private static final ThreadLocal<Boolean> skipFlags = new ThreadLocal<>();

    private MaskManager() {
    }

    public static void registerMaskProcessor(String type, MaskProcessor processor) {
        processorMap.put(type, processor);
    }

    public static boolean getSkipFlag() {
        return skipFlags.get() != null;
    }

    public static <T> T execWithoutMask(Supplier<T> supplier) {
        T var1;
        try {
            skipMask();
            var1 = supplier.get();
        } finally {
            restoreMask();
        }

        return var1;
    }

    public static void execWithoutMask(Runnable runnable) {
        try {
            skipMask();
            runnable.run();
        } finally {
            restoreMask();
        }

    }

    private static void skipMask() {
        skipFlags.set(Boolean.TRUE);
    }

    private static void restoreMask() {
        skipFlags.remove();
    }

    public static String mask(String type, String data) {
        Boolean skipMask = skipFlags.get();
        if (skipMask != null) {
            return data;
        } else {
            MaskProcessor maskProcessor = processorMap.get(type);
            if (maskProcessor == null) {
                throw new DarlingException("找不到数据脱敏类型为'" + type + "'的处理器");
            } else {
                return maskProcessor.mask(data);
            }
        }
    }

    static {
        registerMaskProcessor(Mask.MOBILE, Mask.MOBILE_PROCESSOR);
        registerMaskProcessor(Mask.FIXED_PHONE, Mask.FIXED_PHONE_PROCESSOR);
        registerMaskProcessor(Mask.ID_CARD_NUMBER, Mask.ID_CARD_NUMBER_PROCESSOR);
        registerMaskProcessor(Mask.CHINESE_NAME, Mask.CHINESE_NAME_PROCESSOR);
        registerMaskProcessor(Mask.ADDRESS, Mask.ADDRESS_PROCESSOR);
        registerMaskProcessor(Mask.EMAIL, Mask.EMAIL_PROCESSOR);
        registerMaskProcessor(Mask.PASSWORD, Mask.PASSWORD_PROCESSOR);
        registerMaskProcessor(Mask.CAR_LICENSE, Mask.CAR_LICENSE_PROCESSOR);
        registerMaskProcessor(Mask.BANK_CARD_NUMBER, Mask.BANK_CARD_PROCESSOR);
    }
}

